package com.dragon.design.pattern.creational.singleton;

import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author dragon
 * @version V1.0.0-RELEASE
 * @date 2019/5/16 10:29
 */
public class EnumInstanceTest {

    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        EnumInstance instance = EnumInstance.getInstance();
        System.out.println("instance:" + instance);
        instance.printTest();

        /**
         * 序列化与反序列化,对枚举类型的影响
         */
//        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("enumInstance_file")));
//        oos.writeObject(instance);
//        oos.flush();
//        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("enumInstance_file")));
//        EnumInstance newInstance = (EnumInstance) ois.readObject();
//        System.out.println("newInstance:" + newInstance);
//        System.out.println(instance == newInstance);

        instance.setData(new Object());
        System.out.println("object:" + instance.getData());
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("enumInstance_file")));
        oos.writeObject(instance);
        oos.flush();
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("enumInstance_file")));
        EnumInstance newInstance = (EnumInstance) ois.readObject();
        System.out.println("newObject:" + newInstance.getData());
        System.out.println(instance.getData() == newInstance.getData());
        /**
         * 枚举类型能够避免反射攻击,因为在Constructor判断是否修改修改的类型为枚举类型,如果为枚举类型,则抛出异常
         */
//        Class c = EnumInstance.class;
//        Constructor constructor = c.getDeclaredConstructor(String.class, int.class);
//        constructor.setAccessible(true);
//        EnumInstance newInstance = (EnumInstance) constructor.newInstance("INSTANCE", 2);
//        System.out.println("newInstance:" + newInstance);
//        System.out.println(instance == newInstance);

    }
}
